import { pageInstructReceipt } from '@/services/api/api-instruct-receipt';
import { DownloadOutlined, UserOutlined } from '@ant-design/icons';
import { ProList } from '@ant-design/pro-components';
import { ActionType } from '@ant-design/pro-table';
import { useModel } from '@umijs/max';
import { Avatar, Button, Divider, Space, Tag, Typography, Upload, UploadFile } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';
import UpdateReceipt from './UpdateReceipt';

interface ListReceiptProps {
  recordId: string | undefined;
  deadlineTime: string;
  type?: 1 | 2;
  createdCombineId?: string;
  createdOrganization?: {
    id: string;
    name: string;
  };
  reload?: boolean;
  onSelelctCreatedOrganization?: (createdOrganizationId: string) => void;
  onCloseCreatedOrganization?: () => void;
}

const ListReceipt: React.FC<ListReceiptProps> = ({
  recordId,
  type,
  deadlineTime,
  createdCombineId,
  createdOrganization,
  reload,
  onSelelctCreatedOrganization,
  onCloseCreatedOrganization,
}) => {
  const access = useAccess();
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  const actionRef = useRef<ActionType>();
  const [search, setSearch] = useState<string>('');

  const [selelctCreatedOrganization, setSelectCreatedOrganization] = useState<{
    id: string;
    name: string;
  }>();



  /**
   * 请求网络
   * @param value
   */
  const request = async (params = {}) => {
    const response = await pageInstructReceipt({
      type,
      recordId,
      createdCombineId,
      createdOrganizationIds: selelctCreatedOrganization ? [selelctCreatedOrganization?.id] : [],
      search: search,
      ...params,
    });
    return Promise.resolve({
      data: response.data.data,
      total: response.data.total,
      success: response.code === 0,
    });
  };

  useEffect(() => {
    actionRef.current?.reloadAndRest();
  }, [createdCombineId]);

  useEffect(() => {

    if (createdOrganization) {
      setSelectCreatedOrganization({
        id: createdOrganization?.id,
        name: createdOrganization?.name,
      })
    } else {
      setSelectCreatedOrganization(undefined)
    }


    actionRef.current?.reloadAndRest();

  }, [createdOrganization]);


  useEffect(() => {
    actionRef.current?.reload();
  }, [reload]);

  return (
    <ProList<InstructReceiptData.ReceiptPage>
      headerTitle={<div><div>截止日期：<span style={{
        color: 'red'
      }}>{deadlineTime}</span></div>

        {access.宣传指令x配置x管理员 && selelctCreatedOrganization != undefined && <Tag style={{
          marginTop: '12px',
          fontSize: '14px'
        }} color="success" closeIcon onClose={() => {
          setSelectCreatedOrganization(undefined)
          actionRef.current?.reloadAndRest();

          if (onCloseCreatedOrganization) {
            onCloseCreatedOrganization();
          }
        }}>
          {selelctCreatedOrganization?.name}
        </Tag>
        }
      </div>}
      ghost
      request={request}
      actionRef={actionRef}
      rowKey="id"
      dateFormatter="string"
      pagination={{
        showQuickJumper: true,
        showSizeChanger: true,
        defaultPageSize: 20,
      }}
      toolbar={{
        search: {
          allowClear: true,
          onSearch: (value: string) => {
            setSearch(value);
            actionRef.current?.reloadAndRest();
          },
        },
        actions: [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              actionRef.current?.reloadAndRest();
            }}
          >
            刷新
          </Button>,
        ],
      }}
      metas={{
        title: {
          dataIndex: 'createdOrganizationName',
          render: (dom, entity) => {
            return (
              <Space size={0}>
                <Tag color={entity.type === 2 ? '#87d068' : '#1AA15F'}>
                  {entity.type === 2 ? '已回执' : '已阅读'}
                </Tag>
                <Avatar
                  size="small"
                  icon={<UserOutlined />}
                  src={entity.createdOrganizationAvatar}
                />
                <a style={{
                  textDecoration: 'none',
                  color: 'inherit'
                }} onClick={() => {
                  setSelectCreatedOrganization({
                    id: entity.createdOrganizationId,
                    name: entity.createdOrganizationName,
                  })
                  if (onSelelctCreatedOrganization) {
                    onSelelctCreatedOrganization(entity.createdOrganizationId);
                  }
                  actionRef.current?.reloadAndRest()
                }}><span
                  style={{
                    marginLeft: '5px',
                    marginRight: '5px',
                  }}
                >
                    {entity.createdOrganizationName}
                  </span>
                  -
                  <span
                    style={{
                      marginLeft: '5px',
                    }}
                  >
                    {entity.createdAccountName}
                  </span>
                </a>
                {
                  access.宣传指令x配置x接收者 && currentUser?.id === entity.createdAccountId && (
                    <UpdateReceipt
                      item={entity}
                      onSave={() => {
                        actionRef.current?.reload();
                      }}
                    />
                  )
                }
              </Space >
            );
          },
        },
        description: {
          dataIndex: 'content',
          render: (dom, entity) => {
            return entity.content ? (
              <div>
                <div style={{ display: 'flex', alignItems: 'flex-start' }}>
                  <div style={{ width: 65, whiteSpace: 'nowrap' }}></div>
                  <Typography.Paragraph
                    style={{ flexGrow: 1, margin: 0 }}
                    type="secondary"
                    ellipsis={{
                      rows: 2,
                      expandable: true,
                      onEllipsis: (ellipsis) => {
                        console.log('Ellipsis changed:', ellipsis);
                      },
                    }}
                    copyable
                  >
                    {entity.content}
                  </Typography.Paragraph>
                </div>
                {entity?.attachments && entity?.attachments.length > 0 && (
                  <>
                    {/* <Divider /> */}
                    {/* <div
                      style={{
                        textAlign: 'right',
                      }}
                    >
                      <Button
                        type="primary"
                        key="import"
                        size="small"
                        icon={<DownloadOutlined />}
                        onClick={() => {
                          entity?.attachments.forEach(function (item) {
                            window.open(item.content, '_blank');
                          });
                        }}
                      >
                        全部下载
                      </Button>
                    </div> */}

                    <Upload
                      multiple
                      fileList={entity?.attachments.map((item) => {
                        return {
                          uid: item.id,
                          name: item.name,
                          url: item.content,
                          mimeType: item.mimeType,
                          status: 'done',
                        };
                      })}
                      showUploadList={{
                        // downloadIcon: (
                        //   <div
                        //     style={{ marginLeft: '-100px', padding: '17px 0', marginTop: '-15px' }}
                        //   >
                        //     <DownloadOutlined
                        //       style={{
                        //         marginRight: '10px',
                        //       }}
                        //     />
                        //     点击下载
                        //   </div>
                        // ),
                        showRemoveIcon: false,
                        showDownloadIcon: true,
                      }}
                      onPreview={async (file: UploadFile) => {


                      }}
                    />
                  </>
                )}
              </div>
            ) : (
              <></>
            );
          },
        },
        actions: {
          render(dom, entity, index, action, schema) {
            return (
              <a
                style={{
                  color: entity.isDeadlineTimeReceipt == 1 ? '#faad14' : '',
                }}
              >
                {entity.createdTime}
              </a>
            );
          },
        },
      }}
    />
  );
};

export default ListReceipt;
